<?php
/**
 * Created by b17
 * 2/15/12 7:53 PM
 */

class Admin_MessagesController extends G4T_CrudController
{
    public function indexAction()
    {
        $messages = $this->manager->getList();
        $this->view->items = $messages;
    }

    /**
     * Возвращает менеджер для работы с сущностью.
     *
     * @return \Managers\CrudManager
     */
    protected function getManager()
    {
        return new \Managers\DeliveryMessages();
    }

    /**
     * Возвращает строителя форм для создания форм.
     * @return \G4T\Form\FormBuilder
     */
    protected function createFormBuilder()
    {
        $form = \G4T\Form\FormBuilder::createFormBuilder(\Managers\DeliveryMessages::TABLE)
            ->addField('title', 'string', array('class' => 'medium-input', 'label' => 'Subject'))
            ->addField('content', 'text', array('label' => 'Content'))
            ->addField('startTime', 'datetime', array('label' => 'Start time', 'required' => false))
            ->addField('token', 'hash')
            ->addField('submit', 'submit', array('label' => 'Save', 'class' => 'btn btn-primary'));

        return $form;
    }

    /**
     * Переход при не найденой сущности.
     * @param $id
     */
    protected function redirectWhenNotFound($id = null)
    {
        $this->_flashMessenger->addMessage('Record not found.', Lib_Flash::ERROR, Lib_Flash::LATER);
        $this->_redirect('/admin/messages');
    }

    /**
     * Переход при успешном изменении объекта.
     * @param $entity
     */
    protected function redirectWhenSuccess($entity = null)
    {
        $this->_flashMessenger->addMessage('Successfully saved.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        $this->_redirect('/admin/messages');
    }

    public function nowAction()
    {
        try {
            $this->manager->deliverNow($this->_getParam('id'));
            $this->_flashMessenger->addMessage('Message will be sent in a few minutes.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        } catch (LogicException $e) {
            $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::LATER);
        } catch (Exception $e) {
            $this->handleException($e);
        }
        $this->_redirect('/admin/messages');
    }
}
